package com.ee.bruscar.generator.model;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TemplateInterface
{
	private Class<?> interfaceToHonour;
	
	public TemplateInterface( Class<?> interfaceToHonuour )
	{
		this.interfaceToHonour = interfaceToHonuour;
	}
	
	public Map<String, TemplateClass> getCustomClasses()
	{
		TemplateMethod[] methods = wrapMethods( interfaceToHonour.getMethods() );
		Map<String, TemplateClass> map = new HashMap<String,TemplateClass>();
		
		for( int i = 0 ; i < methods.length; i++ )
		{
			if( methods[i].isReturnTypeList() )
			{
				TemplateClass listReturnType = methods[i].getListReturnType();
				map.put( listReturnType.getClassName(), listReturnType );
			}
			else
			{
				TemplateClass clazz = methods[i].getReturnType();
				clazz.getCustomClassesFromSetters( map );
			}
		}
		return map;
	}
	
	public Map<String, TemplateClass> getCustomListSetterClasses()
	{
		TemplateMethod[] methods = wrapMethods( interfaceToHonour.getMethods() );
		Map<String, TemplateClass> map = new HashMap<String,TemplateClass>();
		
		List<TemplateClass> setterListClasses;
		
		for( int i = 0 ; i < methods.length; i++ )
		{
			if( methods[i].isReturnTypeList() )
			{
				TemplateClass listReturnType = methods[i].getListReturnType();
				setterListClasses = listReturnType.getCustomSetterListClasses();
			}
			else
			{
				TemplateClass clazz = methods[i].getReturnType();
				setterListClasses = clazz.getCustomSetterListClasses();
			}
			
			for( TemplateClass clazz : setterListClasses )
			{
				map.put( clazz.getClassName(), clazz );
			}
		}
		return map;
	}
	
	public TemplateMethod[] getMethods()
	{
		return wrapMethods( interfaceToHonour.getMethods() );
	}
	
	private TemplateMethod[] wrapMethods(Method[] methods)
	{
		TemplateMethod[] wrapped = new TemplateMethod[methods.length];
		
		for( int i = 0 ; i < methods.length ; i++ )
		{
			wrapped[i] = new TemplateMethod( methods[i] );
		}
		return wrapped;
	}
	
	public List<String> getImports()
	{
		List<String> imports = new ArrayList<String>();
		
		//TODO: need to fine a realworld sample to see what is required here.
		//For now just adding the standard imports
		
		imports.add("java.util.Date" );
		imports.add("java.util.List" );
		imports.add("java.util.ArrayList" );
		Map<String, TemplateClass> map = getCustomClasses();
		
		Set<String> set = map.keySet();
		Iterator<String> iterator = set.iterator();
		
		while( iterator.hasNext() )
		{
			String key = iterator.next();
			TemplateClass clazz = map.get(key );
			imports.add( clazz.getClassName() );
		}
		
		return imports;
	}
}
